import pymysql


class MySQLHelper:
    def __init__(self, host, port, user, password, database):
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.database = database
        self.conn = pymysql.connect(host=host, port=port, user=user, password=password, database=database)

    def execute(self, sql, args=None):
        with self.conn.cursor() as cursor:
            cursor.execute(sql, args)
            self.conn.commit()
            return cursor.lastrowid

    def fetch_all(self, sql, args=None):
        with self.conn.cursor() as cursor:
            cursor.execute(sql, args)
            return cursor.fetchall()

    def fetch_one(self, sql, args=None):
        with self.conn.cursor() as cursor:
            cursor.execute(sql, args)
            return cursor.fetchone()

    def insert(self, table, data):
        sql = f"INSERT INTO {table} ({','.join(data.keys())}) VALUES ({','.join(['%s'] * len(data))})"
        return self.execute(sql, tuple(data.values()))

    def update(self, table, data, where):
        sql = f"UPDATE {table} SET {','.join([f'{k}=%s' for k in data.keys()])} WHERE {where}"
        return self.execute(sql, tuple(data.values()))

    def delete(self, table, where):
        sql = f"DELETE FROM {table} WHERE {where}"
        return self.execute(sql)

    def select(self, table, where):
        sql = f"SELECT * FROM {table} WHERE {where}"
        return self.fetch_all(sql)
